package cn.kgc.userprovider.service.impl;

import cn.kgc.qg.pojo.user.QgUser;
import cn.kgc.qg.service.user.TokenService;
import cn.kgc.qg.utils.MD5Util;
import cn.kgc.qg.utils.RedisUtil;
import cn.kgc.qg.utils.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("tokenService")
public class TokenServiceImpl implements TokenService {
    @Override
    public String generateToken(String userAgent, QgUser qgUser) {
        // TODO
        //白佳庆的提交
        // 生成TOKEN   pc/mobile-userid-时间戳-MD5(用户标识)取六位
        StringBuffer tokenSb = new StringBuffer("");
        // 确保所有的token在redis中都在同一个文件夹下，容易管理
        tokenSb.append("token:");
        if (UserAgentUtil.CheckAgent(userAgent)){
            tokenSb.append("MOBILE-");
        }else{
            tokenSb.append("PC-");
        }
        tokenSb.append(qgUser.getId()+"-");
        tokenSb.append(System.currentTimeMillis()+"-");
        tokenSb.append(StringUtils.substring(MD5Util.MD5EncodeUtf8(userAgent),0,6));
        System.out.println(">>>>>>>>"+qgUser.getRealName() + "的token 生成完成");
        System.out.println("<<<<<<<<"+tokenSb.toString());
        System.out.println("宋英泽提交");
        return tokenSb.toString();
    }

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void saveToken(String token , QgUser qgUser , String userAgent){
        if (UserAgentUtil.CheckAgent(userAgent)){
            redisUtil.setStr(token, JSON.toJSONString(qgUser) , -1L);
        }else{
            redisUtil.setStr(token,JSON.toJSONString(qgUser), 120L);
        }
    }


}
